package cn.news.xinhuanet.application.filter;


import cn.news.xinhuanet.utils.HomeConstants;
import org.apache.log4j.Logger;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

/**
 * 此过滤器负责对编码进行自动处理，以及执行URL映射规则
 *
 * @author xinhua http://www.oschina.net/code/snippet_12_2832
 */
public abstract class AbstactorURLMappingFilter implements Filter {
    private static Logger logger = Logger.getLogger(AbstactorURLMappingFilter.class);
    private String[] ignoreFilter;
    private String login;

    public void init(FilterConfig config) throws ServletException {
        String encoding = config.getInitParameter("encoding");
        String ignoreTypes_ = config.getInitParameter("ignoreFilter");
        String login = config.getInitParameter("login");
        if (encoding != null && !"".equals(encoding)) {
            HomeConstants.encoding = encoding;
        }
        if (null != ignoreTypes_ && !"".equals(ignoreTypes_)) {
            this.ignoreFilter = ignoreTypes_.split(",");
        }
        this.login = login;
        logger.info("拦截器 initialization started");
    }

    public void destroy() {
        logger.info("拦截器 destroy ");
    }

    public void doFilter(ServletRequest req, ServletResponse res, FilterChain filter) throws UnsupportedEncodingException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        response.setContentType("text/json;charset=" + HomeConstants.encoding);
        request.setCharacterEncoding(HomeConstants.encoding);
        try {

            doFilter(filter, request, response);//放行。让其走到下个链或目标资源中
        } catch (Exception e) {
            logger.error("URLMappingFilter:", e);
            throw new ServletException("权限拦截异常");
        }

    }


    private void doFilter(FilterChain filter, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        filter.doFilter(request, response);//放行。让其走到下个链或目标资源中
    }


}
